package com.puzzlebazar.client.main.model;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.puzzlebazar.client.main.model.PuzzleListInfoFactory.PuzzleListInfoCreator;
import com.puzzlebazar.client.puzzleinfo.PuzzleInfo;
import com.puzzlebazar.client.services.PuzzleServiceAsync;
import com.puzzlebazar.client.services.ServiceFactory;
import com.puzzlebazar.client.user.UserInfo;
import com.puzzlebazar.client.util.TextUtil;

public class PuzzleListInfoSearch extends PuzzleListInfoWithType {

	private static final String INFO_TYPE_SEARCH = "SEARCH";
	private static final String GENRES = "GENRES";
	
	/**
	 * Register this puzzle list information structure
	 * 
	 * @param factory The factory to register with
	 */
	public static void register( PuzzleListInfoFactory factory ) {
		factory.registerPuzzleListInfo( INFO_TYPE_SEARCH, new PuzzleListInfoCreator() {
			@Override
			public PuzzleListInfo createPuzzleListInfo(HashMap<String, String> params) {
				return new PuzzleListInfoSearch( params );
			}		
		});
	}	
	
	private final Vector<String> genreList;
	
	
	/**
	 * Creates a puzzle list information structure for a generic search query
	 * 
	 * @param params The parameters to use in the search query
	 */
	public PuzzleListInfoSearch(HashMap<String, String> params) {
		super(INFO_TYPE_SEARCH, params);
		genreList = TextUtil.split( params.remove(GENRES), "," );
		appendCustomParameters();
	}

	/**
	 * Creates a puzzle list information structure for a generic search query
	 * given the structured parameters
	 * 
	 * @param listType The list type to use
	 */
	public PuzzleListInfoSearch( ListType listType, Vector<String> genreList ) {
		super(INFO_TYPE_SEARCH, listType);
		this.genreList = genreList;
		appendCustomParameters();
	}
	
	@Override
	public void callService(AsyncCallback<List<PuzzleInfo>> callback) {
		PuzzleServiceAsync puzzleService = ServiceFactory.getPuzzleService(); 		
		puzzleService.getPuzzleList(listType, genreList, callback );
	}

	@Override
	public boolean canUserGetList(UserInfo userInfo) {
		if( !super.canUserGetList(userInfo) )
			return false;
		return true;
	}
	
	@Override
	public String getName() {
		return "Generic search";
	}

	/**
	 * Append the custom parameters for this class. 
	 * Should only be called by a constructor.
	 */
	private void appendCustomParameters() {
		appendCustomParam( GENRES, TextUtil.join( genreList, "," ) );
	}

}
